<!-- 文字转语音 -->
<script setup>
const props = defineProps({
  text: {
    type: String,
    required: true,
  },
  fixed: {
    type: Boolean,
    default: true,
  },
  btnText: {
    type: String,
    default: '听',
  },
  bottom: {
    type: String,
    default: '100px',
  },
  right: {
    type: String,
    default: '100px',
  },
  // size: {
  //   type: String,
  //   default: '50px',
  // },
  fontSize: {
    type: String,
    default: '20px',
  },
})
const text = ref(props.text)
const canSpeak = ref(false)
const isSpeaking = ref(false)
const isPaused = ref(false)
const progress = ref(0)
const utterance = ref(null)
function setText(val) {
  text.value = val
}
function updateProgress() {
  if (utterance.value && utterance.value.elapsedTime > 0) {
    const totalDuration = utterance.value.duration
    const elapsed = utterance.value.elapsedTime
    progress.value = Math.round((elapsed / totalDuration) * 100)
    ElMessage.info(`朗读进度：${progress.value}%`)
  }
}

function speakText() {
  if (!window.speechSynthesis) {
    ElMessage.error('您的浏览器不支持 Web Speech API')
    return
  }
  // 取消之前的朗读
  window.speechSynthesis.cancel()
  isPaused.value = false
  utterance.value = new SpeechSynthesisUtterance(text.value)
  utterance.value.lang = 'zh-CN'

  // 监听结束事件
  utterance.value.onend = () => {
    isSpeaking.value = false
  }

  // 监听进度变化
  utterance.value.onboundary = (event) => {
    if (event.name === 'word') {
      updateProgress()
    }
  }
  // 开始朗读
  window.speechSynthesis.speak(utterance.value)
  isSpeaking.value = true
}

function toggleSpeak() {
  if (!canSpeak.value) {
    ElMessage.error('当前浏览器不支持朗读api，请切换至谷歌浏览器')
    return
  }
  if (isSpeaking.value) {
    if (window.speechSynthesis.paused) {
      // 暂停状态 点击之后继续播放
      ElMessage.info('继续播放')
      window.speechSynthesis.resume()
      isPaused.value = false
      // const obj = {
      //   paused: window.speechSynthesis.paused,
      //   speaking: window.speechSynthesis.speaking,
      //   pending: window.speechSynthesis.pending,
      // }
      // ElMessage.info(`继续播放:${JSON.stringify(obj)}`)
    }
    else if (window.speechSynthesis.speaking) {
      // 正在播放 点击后暂停
      ElMessage.info('暂停播放')
      window.speechSynthesis.pause()
      isPaused.value = true
      // const obj = {
      //   paused: window.speechSynthesis.paused,
      //   speaking: window.speechSynthesis.speaking,
      //   pending: window.speechSynthesis.pending,
      // }
      // ElMessage.info(`暂停播放:${JSON.stringify(obj)}`)
    }
  }
  else {
    // 开始朗读
    ElMessage.info('开始朗读')
    speakText(props.text)
  }
}
function stopSpeak() {
  window.speechSynthesis?.cancel()
  ElMessage.success('停止播放')
  isSpeaking.value = false
  isPaused.value = false
}
// 组件挂载时检查是否支持 Web Speech API
onMounted(() => {
  if (!window.speechSynthesis) {
    canSpeak.value = false
  }
  else {
    canSpeak.value = true
  }
})
onUnmounted(() => {
  window.speechSynthesis?.cancel?.()
})
const route = useRoute()
watch(route, () => {
  window.speechSynthesis?.cancel?.()
})
defineExpose({
  setText,
})
</script>

<template>
  <div
    class="flex cursor-pointer items-center justify-center rounded-25px p-4px text-20px text-#35B389"
    :class="{ fixed, 'bg-#EBF7F3 ': isSpeaking }"
    :style="{ fontSize }"
  >
    <div class="relative left-0 top-0 z-0 h-30px flex items-center justify-center transition-all duration-300" hover="opacity-70" :class="{ 'w-80px': isSpeaking, 'w-30px': !isSpeaking }">
      <div class="w-full flex items-center justify-around" :class="{ 'px-10px': isSpeaking }">
        <!-- <span v-if="!isSpeaking" class="" title="播放" @click="toggleSpeak">
          {{ btnText }}
        </span> -->
        <span v-if="true" class="flex flex-1 items-center justify-center" @click="toggleSpeak">
          <i v-if=" !isSpeaking || isPaused" class="i-ri:play-circle-line" title="继续播放" />
          <i v-if=" isSpeaking && !isPaused" class="i-ri:pause-circle-line" title="暂停播放" />
        </span>
        <span v-if="isSpeaking" class="flex flex-1 items-center justify-center" @click.stop.capture="stopSpeak">
          <i class="i-ri:stop-circle-line" title="停止播放" />
        </span>
      </div>
      <!-- <span v-if="!isSpeaking">
        {{ btnText }}
      </span> -->
    </div>
  </div>
</template>

<style scoped>
</style>
